<script setup>
import { ref, onMounted, onUnmounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { getArticleList, getHotArticles, getArticlesByTag, getFavoriteArticles, getReadArticles, getLikedArticles, getUserArticles } from '../api/article'
import { getTags } from '../api/tag'
import { getUserStats } from '../api/user'
import { Star, Collection, View, Pointer, Loading, ChatLineRound, ArrowDown, Edit } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { generateColor } from '../utils/avatar'
import { formatDate } from '../utils/date'

const router = useRouter()
const userStore = useUserStore()

const articles = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const hasMore = ref(true)
const total = ref(0)

// 添加当前列表类型
const currentListType = ref('all')  // 'all', 'favorite', 'read', 'liked'

// 修改加载文章列表的方法
const loadArticles = async (append = false) => {
  if (!append) {
    currentPage.value = 1
    articles.value = []
    hasMore.value = true
  }

  if (!hasMore.value || loading.value) return

  try {
    loading.value = true
    let res

    // 根据不同类型加载不同的文章列表
    switch (currentListType.value) {
      case 'article':
        res = await getUserArticles(currentPage.value, pageSize.value)
        break
      case 'favorite':
        res = await getFavoriteArticles(currentPage.value, pageSize.value)
        break
      case 'read':
        res = await getReadArticles(currentPage.value, pageSize.value)
        break
      case 'liked':
        res = await getLikedArticles(currentPage.value, pageSize.value)
        break
      case 'tag':
        if (selectedTagId.value) {
          res = await getArticlesByTag(selectedTagId.value, currentPage.value, pageSize.value)
        } else {
          res = await getArticleList(currentPage.value, pageSize.value)
        }
        break
      default:
        res = await getArticleList(currentPage.value, pageSize.value)
    }

    if (append) {
      articles.value.push(...res.data.records)
    } else {
      articles.value = res.data.records
    }

    total.value = res.data.total
    hasMore.value = res.data.records.length === pageSize.value
    if (hasMore.value) {
      currentPage.value++
    }
  } catch (error) {
    console.error('Failed to load articles:', error)
    ElMessage.error('加载文章失败')
  } finally {
    loading.value = false
  }
}

const handleScroll = () => {
  const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
  const clientHeight = document.documentElement.clientHeight
  const scrollHeight = document.documentElement.scrollHeight

  if (scrollHeight - scrollTop - clientHeight <= 100 && hasMore.value && !loading.value) {
    loadArticles(true)
  }
}

// 新增数据
const hotArticles = ref([])
const tags = ref([])

// 用户统计数据
const userStats = ref({
  articleCount: 0,
  viewCount: 0,
  likeCount: 0,
  favoriteCount: 0,
  readCount: 0,
  userLikeCount: 0
})

// 加载用户统计数据
const loadUserStats = async () => {
  if (!userStore.isLoggedIn) return
  const res = await getUserStats()
  userStats.value = res.data
}

// 添加跳转到文章详情的方法
const goToDetail = (articleId) => {
  router.push(`/article/${articleId}`)
}


// 加载热门文章
const loadHotArticles = async () => {
  const res = await getHotArticles()
  hotArticles.value = res.data
}

// 加载标签
const loadTags = async () => {
  const res = await getTags()
  tags.value = res.data
}

// 当前选中的标签
const selectedTagId = ref(null)

// 根据标签筛选
const filterByTag = async (tagId) => {
  if (selectedTagId.value === tagId) {
    selectedTagId.value = null
    currentListType.value = 'all'
    await loadArticles()
  } else {
    selectedTagId.value = tagId
    currentListType.value = 'tag'
    loading.value = true
    currentPage.value = 1
    hasMore.value = true
    
    const res = await getArticlesByTag(tagId, currentPage.value, pageSize.value)
    articles.value = res.data.records
    total.value = res.data.total
    hasMore.value = res.data.records.length === pageSize.value
    if (hasMore.value) {
      currentPage.value++
    }
    loading.value = false
  }
}

// 修改切换列表类型的方法
const switchListType = (type) => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    return
  }

  // 如果点击当前类型，或者点击首页
  if (type === currentListType.value || type === 'all') {
    currentListType.value = 'all'
    selectedTagId.value = null  // 清除标签筛选
    loadArticles()
  } else {
    currentListType.value = type
    loadArticles()
  }
}

// 添加导航栏点击首页的处理
const handleHomeClick = () => {
  currentListType.value = 'all'
  selectedTagId.value = null
  loadArticles()
}

// 监听用户登录状态
watch(() => userStore.isLoggedIn, (newValue) => {
  if (newValue) {
    loadUserStats()
  }
}, { immediate: true })  // immediate: true 确保组件创建时就执行一次

onMounted(() => {
  loadArticles()
  loadHotArticles()
  loadTags()
  window.addEventListener('scroll', handleScroll)
  // 将处理方法暴露给全局
  window.handleHomeClick = handleHomeClick
})

onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll)
  // 清理全局方法
  window.handleHomeClick = null
})
</script>

<template>
  <div class="home-container">
    <div class="main-content">
      <!-- 左侧文章列表 -->
      <div class="article-list">
        <el-empty
            v-if="!loading && articles.length === 0"
            description="暂无文章"
        >
        </el-empty>

        <div v-else>
          <div v-loading="loading">
            <div v-for="article in articles" :key="article.id" class="article-item" @click="goToDetail(article.id)">
              <!-- 添加封面图容器 -->
              <div class="cover-image" v-if="article.coverImage">
                <img :src="article.coverImage" alt="封面图">
              </div>

              <h2 class="title">{{ article.title }}</h2>
              <p class="description">{{ article.description }}</p>
              <div class="meta">
                <div class="left">
                  <el-avatar
                      :size="24"
                      :src="article.authorAvatar"
                      v-if="article.authorAvatar">
                  </el-avatar>
                  <el-avatar
                      :size="24"
                      v-else
                      :style="{
                                backgroundColor: generateColor(article.authorName || ''),
                                color: '#fff',
                                fontSize: '16px'
                              }">
                    {{ (article.authorName || '').charAt(0).toUpperCase() }}
                  </el-avatar>
                  <span class="author">{{ article.authorName }}</span>
                  <span class="date">{{ formatDate(article.createTime) }}</span>

                  <!-- 添加标签到时间后面 -->
                  <div class="article-tags" v-if="article.tags && article.tags.length">
                    <el-tag
                        v-for="tag in article.tags"
                        :key="tag.id"
                        class="tag-item"
                        size="small"
                        :style="{ backgroundColor: tag.color }"
                    >
                      {{ tag.name }}
                    </el-tag>
                  </div>
                </div>
                <div class="stats">
                  <span class="stat-item">
                      <el-icon><View /></el-icon>
                      {{ article.viewCount || 0 }}
                  </span>
                  <span class="stat-item">
                      <el-icon><Pointer /></el-icon>
                      {{ article.likeCount || 0 }}
                  </span>
                  <span class="stat-item">
                      <el-icon><ChatLineRound /></el-icon>
                      {{ article.commentCount || 0 }}
                  </span>
                </div>
              </div>
            </div>
          </div>

          <!-- 加载更多提示 -->
          <div v-if="loading" class="loading-more">
            <el-icon class="is-loading"><Loading /></el-icon>
            <span>加载中...</span>
          </div>
          <div v-else-if="!hasMore && articles.length > 0" class="no-more">
            没有更多了
          </div>
        </div>
      </div>

      <!-- 右侧边栏 -->
      <div class="sidebar">
        <!-- 个人信息卡片 -->
        <div class="sidebar-card user-card">
          <div class="user-info">
            <el-avatar
                :size="64"
                :src="userStore.currentUser?.avatar"
                v-if="userStore.currentUser?.avatar"
            />
            <el-avatar
                :size="64"
                v-else
                :style="{
                                backgroundColor: generateColor(userStore.currentUser?.username),
                                color: '#fff',
                                fontSize: '32px'
                            }"
            >
              {{ userStore.currentUser?.username?.charAt(0).toUpperCase() }}
            </el-avatar>
            <h3>{{ userStore.currentUser?.nickname || '游客' }}</h3>
            <p class="bio">热爱技术，分享生活</p>
          </div>
          <div class="user-stats">
            <div class="stat-item clickable" @click="switchListType('article')" :class="{ active: currentListType === 'article' }">
              <div class="number">{{ userStats.articleCount || 0 }}</div>
              <div class="label">文章</div>
            </div>
            <div class="stat-item">
              <div class="number">{{ userStats.viewCount || 0 }}</div>
              <div class="label">阅读</div>
            </div>
            <div class="stat-item">
              <div class="number">{{ userStats.likeCount || 0 }}</div>
              <div class="label">获赞</div>
            </div>
            <div class="stat-item clickable" @click="switchListType('favorite')" :class="{ active: currentListType === 'favorite' }">
              <div class="number">{{ userStats.favoriteCount || 0 }}</div>
              <div class="label">收藏</div>
            </div>
            <div class="stat-item clickable" @click="switchListType('read')" :class="{ active: currentListType === 'read' }">
              <div class="number">{{ userStats.readCount || 0 }}</div>
              <div class="label">已读</div>
            </div>
            <div class="stat-item clickable" @click="switchListType('liked')" :class="{ active: currentListType === 'liked' }">
              <div class="number">{{ userStats.userLikeCount || 0 }}</div>
              <div class="label">点赞</div>
            </div>
          </div>

          <!-- 添加写文章按钮 -->
          <div v-if="userStore.isLoggedIn">
            <el-button type="primary" @click="router.push('/write')" class="write-btn">
              <el-icon><Edit /></el-icon>
              &nbsp;&nbsp;写文章
            </el-button>
          </div>
        </div>

        <!-- 热门文章 -->
        <div class="sidebar-card hot-articles">
          <h3 class="card-title">
            <el-icon><Star /></el-icon>
            热门文章
          </h3>
          <el-empty
              v-if="hotArticles.length === 0"
              description="暂无热门文章"
              :image-size="60"
          />
          <ul v-else class="article-list">
            <li v-for="article in hotArticles" :key="article.id"
                @click="goToDetail(article.id)"
                class="hot-article-item">
              <span class="title">{{ article.title }}</span>
              <span class="view-count">{{ article.viewCount }}阅读</span>
            </li>
          </ul>
        </div>

        <!-- 标签云 -->
        <div class="sidebar-card tag-cloud">
          <h3 class="card-title">
            <el-icon><Collection /></el-icon>
            标签云
          </h3>
          <el-empty
              v-if="tags.length === 0"
              description="暂无标签"
              :image-size="60"
          />
          <div v-else class="tags">
            <el-tag
                v-for="tag in tags"
                :key="tag.id"
                class="tag-item"
                :style="{ backgroundColor: tag.color }"
                @click="filterByTag(tag.id)"
            >
              {{ tag.name }}
            </el-tag>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
/* 定义标签颜色变量 */
$tag-colors: (
  'java': #F56C6C,
  'spring': #67C23A,
  'vue': #409EFF,
  'mysql': #E6A23C,
  'default': #909399
);

@use 'sass:color';

$primary-color: #3eaf7c;
$text-color: #2c3e50;
$border-color: #eaecef;
$bg-light: #f8f9fa;
$transition: all 0.3s ease;

.home-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;

  @media screen and (max-width: 1200px) {
    padding: 10px;
  }
}

.main-content {
  display: grid;
  grid-template-columns: minmax(0, 1fr) 300px;
  gap: 20px;
  align-items: start;
}

.sidebar {
  position: sticky;
  top: 20px;

  .sidebar-card {
    background: #fff;
    border-radius: 12px;
    padding: 20px;
    margin-bottom: 20px;
    border: 1px solid $border-color;

    .card-title {
      font-size: 16px;
      font-weight: 600;
      color: $text-color;
      margin-bottom: 16px;
      display: flex;
      align-items: center;
      gap: 8px;

      .el-icon {
        color: $primary-color;
      }
    }
  }

  .user-card {
    text-align: center;

    .user-info {
      margin-bottom: 20px;

      .el-avatar {
        margin-bottom: 12px;
      }

      h3 {
        font-size: 18px;
        color: $text-color;
        margin-bottom: 8px;
      }

      .bio {
        color: #666;
        font-size: 14px;
      }
    }

    .user-stats {
      display: grid;
      grid-template-columns: repeat(3, 1fr);  // 3列布局
      gap: 12px;
      padding: 15px 0;
      border-top: 1px solid $border-color;
      border-bottom: 1px solid $border-color;
      margin-bottom: 20px;

      .stat-item {
        text-align: center;

        .number {
          font-size: 18px;
          font-weight: 600;
          color: $text-color;
        }

        .label {
          font-size: 12px;
          color: #666;
          margin-top: 4px;
        }
      }
    }
  }

  .hot-articles {
    .article-list {
      list-style: none;
      padding: 0;
      margin: 0;

      .hot-article-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12px 0;
        border-bottom: 1px solid $border-color;
        cursor: pointer;
        transition: $transition;

        &:last-child {
          border-bottom: none;
        }

        &:hover {
          color: $primary-color;
        }

        .title {
          flex: 1;
          font-size: 14px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .view-count {
          font-size: 12px;
          color: #999;
          margin-left: 8px;
        }
      }
    }
  }

  .tag-cloud {
    .tags {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;

      .tag-item {
        cursor: pointer;
        border: none;
        transition: $transition;

        &.el-tag {
          color: #fff;
        }

        &:hover {
          transform: translateY(-2px);
        }
      }
    }
  }
}

.article-list {
  .article-item {
    padding: 30px;
    background: #fff;
    border-radius: 12px;
    margin-bottom: 20px;
    cursor: pointer;
    transition: $transition;
    border: 1px solid $border-color;
    position: relative;
    overflow: hidden;

    // 只在有封面图时才添加右侧边距
    &:has(.cover-image) {
      .title, .description, .meta {
        padding-right: 220px;
      }
    }

    // 修改封面图样式
    .cover-image {
      position: absolute;
      top: 30px;  // 与文章卡片的 padding 对齐
      right: 30px;
      width: 200px;
      height: calc(100% - 60px);  // 减去上下 padding
      border-radius: 8px;
      overflow: hidden;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        transition: transform 0.3s ease;
      }

      &:hover img {
        transform: scale(1.05);
      }
    }

    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 0;
      bottom: 0;
      width: 4px;
      background: $primary-color;
      opacity: 0;
      transition: $transition;
    }

    &:hover {
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
      border-color: $primary-color;

      &::before {
        opacity: 1;
      }

      .title {
        color: $primary-color;
      }
    }

    .title {
      font-size: 22px;
      font-weight: 600;
      color: $text-color;
      margin-bottom: 12px;
      transition: $transition;
      line-height: 1.4;
    }

    .description {
      color: #666;
      font-size: 15px;
      line-height: 1.6;
      margin-bottom: 20px;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      overflow: hidden;
    }

    .meta {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 14px;
      color: #8c8c8c;

      .left {
        display: flex;
        align-items: center;
        gap: 8px;

        .author {
          color: $text-color;
          font-weight: 500;
          margin-right: 10px;

          &:hover {
            color: $primary-color;
          }
        }

        .divider {
          color: #ddd;
        }

        .date {
          margin-right: 10px;
          color: #8c8c8c;
        }
      }

      .stats {
        display: flex;
        gap: 16px;

        .stat-item {
          display: flex;
          align-items: center;
          gap: 4px;
          color: #8c8c8c;

          .el-icon {
            font-size: 16px;
          }
        }
      }
    }
  }
}

.pagination-container {
  margin-top: 40px;
  display: flex;
  justify-content: center;

  :deep(.el-pagination) {
    justify-content: center;

    .el-pagination__total {
      margin-right: 16px;
    }

    .el-pagination__sizes {
      margin-right: 16px;
    }
  }
}

// 响应式处理
@media screen and (max-width: 1200px) {
  .main-content {
    grid-template-columns: 1fr;
  }

  .sidebar {
    display: none;  // 在小屏幕上隐藏侧边栏
  }
}

@media screen and (max-width: 768px) {
  .home-container {
    padding: 10px;
  }

  .article-list {
    .article-item {
      padding: 20px;
      margin-bottom: 15px;

      .title {
        font-size: 18px;
      }

      .description {
        font-size: 14px;
        margin-bottom: 15px;
      }

      .meta {
        flex-direction: column;
        align-items: flex-start;
        gap: 10px;

        .stats {
          width: 100%;
          justify-content: flex-end;
        }
      }
    }
  }
}

.loading-more,
.no-more {
  text-align: center;
  padding: 20px 0;
  color: #999;
  font-size: 14px;

  .el-icon {
    margin-right: 6px;
  }
}

.no-more {
  color: #999;
  font-size: 14px;
  padding: 30px 0;
  position: relative;

  &::before,
  &::after {
    content: '';
    position: absolute;
    top: 50%;
    width: 100px;
    height: 1px;
    background: #eee;
  }

  &::before {
    right: calc(50% + 50px);
  }

  &::after {
    left: calc(50% + 50px);
  }
}

/* 通用标签样式 */
.article-tags, .tag-cloud .tags {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;

  .tag-item {
    border: none;
    cursor: pointer;
    transition: all 0.3s ease;

    &.el-tag {
      color: #fff;
      margin: 0;
      
      &:hover {
        transform: translateY(-2px);
      }
    }
  }
}

/* 文章列表中标签的特殊样式 */
.article-item .meta .left .article-tags {
  display: inline-flex;
  
  .tag-item {
    font-size: 12px;
    padding: 0 8px;
    height: 22px;
    line-height: 22px;
  }
}

.user-stats {
  .stat-item {
    &.clickable {
      cursor: pointer;

      .number {
        color: $primary-color;  // 可点击项的数字显示为主题色
        transition: color 0.3s;  // 添加过渡效果
      }

      &:hover {
        .number {
          color: color.adjust($primary-color, $lightness: 10%); // 使用 color.adjust 替代 lighten
        }
        .label {
          color: $primary-color;  // 悬浮时标签也变绿
        }
      }

      &.active {
        .number {
          font-weight: bold;
        }
      }
    }
  }
}
</style>